import util from '../../utils/util.js';

var subid;
var share_title = "";
var share_image = "";

/** 
 *字符串转json 
 */
function jsonToString(data) {
  return JSON.stringify(data);
}

function updateUserInfo(obj) {

  wx.getUserInfo({
    success: function(res) {
      wx.setStorageSync("nickName", res.userInfo.nickName);
      wx.setStorageSync("avatarUrl", res.userInfo.avatarUrl);

      updateUserAvatar(res.userInfo.avatarUrl);
      console.log("nickName", res);

      obj.setData({
        isScope: true
      })
    },
    fail: function(e) {
      // console.log(e);
      obj.setData({
        isScope: false
      })
    }
  })
}

function showCuPlanAndTask(obj) {
  // var img = "../images/icon_share.png";
  // obj.setData({
  //   list: [{
  //     typeImg: img,
  //     show: true,
  //     listName: '默认计划',
  //     count: '0/0',
  //     item: [{
  //       itemName: '默认任务',
  //       isChecked: false
  //     }]
  //   }]
  // })
}

function updateUserAvatar(avatarUrl) {
  if (wx.getStorageSync("userId") != "" && avatarUrl != "") {

    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true
    })
    wx.request({
      url: getApp().globalData.url + '/loginMain/updateUserAvatar',
      data: util.json2Form({
        "userId": wx.getStorageSync("userId"),
        "avatarUrl": avatarUrl,
        "nickName": wx.getStorageSync("nickName")
      }),
      method: 'POST',
      header: {
        // 'Content-Type': 'application/json'
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideToast();
      }
    })
  }
}

function deleteTask(obj, task_id) {
  wx.showToast({
    title: '加载中',
    icon: 'loading',
    mask: true
  })

  wx.request({
    url: getApp().globalData.url + '/PLanAndTask/deleteTaskById',
    data: util.json2Form({
      "taskId": task_id
    }),
    method: 'POST',
    header: {
      // 'Content-Type': 'application/json'
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {
      wx.hideToast();
      doHttp(obj);
    }
  })
}

function deletePlan(obj, plan_id) {
  wx.showToast({
    title: '加载中',
    icon: 'loading',
    mask: true
  })

  wx.request({
    url: getApp().globalData.url + '/PLanAndTask/deletePlanById',
    data: util.json2Form({
      "planId": plan_id
    }),
    method: 'POST',
    header: {
      // 'Content-Type': 'application/json'
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {
      wx.hideToast();
      doHttp(obj);
    }
  })
}

/**改变列表内打钩和没打钩的排序 */
function setListOrder(obj) {
  for (var x = 0; x < obj.data.list.length; x++) {
    var itemTemp = new Array();
    for (var i = 0; i < obj.data.list[x].item.length; i++) {
      if (!obj.data.list[x].item[i].isChecked) {
        itemTemp.push(obj.data.list[x].item[i]);
      }
    }

    for (var i = 0; i < obj.data.list[x].item.length; i++) {
      if (obj.data.list[x].item[i].isChecked) {
        itemTemp.push(obj.data.list[x].item[i]);
      }
    }

    obj.data.list[x].item = itemTemp;
  }
  obj.setData({
    list: obj.data.list
  })
}

function sendData(obj, cuNum) {
  wx.showToast({
    title: '加载中',
    icon: 'loading',
    mask: true
  })
  var listBody = "";
  for (var i = 0; i < obj.data.list.length; i++) {
    if (i > 0)
      listBody = listBody + "," + JSON.stringify(obj.data.list[i]);
    else
      listBody = JSON.stringify(obj.data.list[i]);
  }
  listBody = "[" + listBody + "]";
  console.log("doSync", wx.getStorageSync("userId"));

  wx.request({
    url: getApp().globalData.url + '/PLanAndTask/doSync',
    data: util.json2Form({
      "key": listBody,
      "userId": wx.getStorageSync("userId"),
      "user_name": wx.getStorageSync("nickName"),
      "avatar_url": wx.getStorageSync("avatarUrl")
    }),
    method: 'POST',
    header: {
      // 'Content-Type': 'application/json'
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {
      wx.hideToast();

      wx.getUserInfo({
        success: function(res) {
          wx.setStorageSync("nickName", res.userInfo.nickName);
          wx.setStorageSync("avatarUrl", res.userInfo.avatarUrl);

          obj.setData({
            isScope: true
          })
        },
        fail: function(e) {
          // console.log(e);
          obj.setData({
            isScope: false
          })
        }
      })

      if (res.data.code == -401) {
        wx.login({
          success: function(e) {
            var code = e.code;

            wx.request({
              url: getApp().globalData.url + '/loginMain/getUserInfo',
              data: {
                js_code: code
              },
              method: 'POST',
              header: {
                // 'Content-Type': 'application/json'
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function(e) {
                wx.setStorageSync("userId", e.data);
                updateUserAvatar(wx.getStorageSync("avatarUrl"));
              }
            })
          },
          fail: function(e) {

          }
        })
      }

      if (res.statusCode != 200 && res.data.code != 1) {
        return;
      }

      // console.log(wx.getStorageSync("isFirst"));
      if (obj.data.list.length > 0) {
        if (wx.getStorageSync("isFirst") == '') {
          obj.setData({
            isArrowShow: "",

          })
          wx.setStorageSync("isFirst", "false");
        }
      }


      cuSelectNum = cuNum;
      obj.setData({
        this_cuSelectNum: cuSelectNum
      })

      doHttp(obj);
    }
  })
}

function setChecked(obj, itemId, is_checked, index) {
  wx.showToast({
    title: '加载中',
    icon: 'loading',
    mask: true
  })

  wx.request({
    url: getApp().globalData.url + '/PLanAndTask/setTaskCheckById',
    data: util.json2Form({
      "taskId": itemId,
      "is_checked": is_checked,
      "userId": wx.getStorageSync("userId")
    }),
    method: 'POST',
    header: {
      // 'Content-Type': 'application/json'
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {
      wx.hideToast();
      console.log("setTaskCheckById", index);

      obj.data.list[cuSelectNum].item[index].creatorImg = res.data.avatar_url;

      /**排序 start */
      setListOrder(obj);
      /**排序 end */
      wx.setStorageSync("list", obj.data.list);
      //zzp_1
      setTitle(obj);
      setListItemCount(obj);
    }
  })
}

function doHttp(obj) {
  wx.showToast({
    title: '加载中',
    icon: 'loading',
    mask: true
  })

  wx.request({
    url: getApp().globalData.url + '/PLanAndTask/getPlanAndTask',
    data: {
      id: wx.getStorageSync("userId")
    },
    method: 'POST',
    header: {
      // 'Content-Type': 'application/json'
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {
      wx.hideToast();
      /**下拉出来的东西 */
      wx.stopPullDownRefresh();

      console.log("getPlanAndTask", res);
      // console.log("2", res);
      if (res.statusCode != 200) {
        wx.showToast({
          title: '连接服务器失败' + res.statusCode,
          icon: 'none',
          mask: true
        })
        return;
      }

      var listTemp = new Array();
      for (var x = 0; x < res.data.length; x++) {
        var itemTemp = new Array();
        for (var y = 0; y < res.data[x].task.length; y++) {
          itemTemp = [{
            itemId: res.data[x].task[y].task_id,
            itemName: res.data[x].task[y].task_title,
            creatorImg: res.data[x].task[y].creatorImg,
            content: "",
            time: "",
            isChecked: res.data[x].task[y].is_checked
          }].concat(itemTemp);
        }
        var isShow = false;
        if (res.data.length - 1 - x == cuSelectNum) {
          isShow = true;
        } else {
          isShow = false;
        }
        // console.log(res.data[x].plan);

        var img = "../images/icon_share.png";
        if (res.data[x].plan.plan_type == 0) {
          img = "../images/icon_share.png";
        } else {
          img = "../images/icon_team.png";
        }

        listTemp = [{
          typeImg: img,
          show: isShow,
          listId: res.data[x].plan.plan_id,
          listName: res.data[x].plan.plan_title,
          count: "0/0",
          item: itemTemp,
          typeStr: res.data[x].plan.plan_type
        }].concat(listTemp);
      }
      var btnText = "";
      if (listTemp.length > cuSelectNum) {
        btnText = listTemp[cuSelectNum].listName;
      } else if (listTemp.length > 0) {
        btnText = listTemp[0].listName;
      }

      if (btnText == "") {
        btnText = "暂无计划";
      }

      obj.setData({
        list: listTemp,
        buttonText: btnText
      })
      setListOrder(obj);

      //zzp_1
      setTitle(obj);
      setListItemCount(obj);

      wx.setStorageSync("list", obj.data.list);

      // if (wx.getStorageSync("list") == null || wx.getStorageSync("list") == "") {
      //   var img = "../images/icon_share.png";
      //   obj.setData({
      //     list: [{
      //       typeImg: img,
      //       show: true,
      //       listName: '默认计划',
      //       count: '0/0',
      //       item: [{
      //         itemName: '默认任务',
      //         isChecked: false
      //       }]
      //     }]
      //   })

      //   sendData(obj);
      // }
    },
    fail: function(e) {
      wx.hideToast();
      console.log("服务器连接失败");
    }
  })
  /**在没有网络的情况下也要保证能用 */
  if (wx.getStorageSync("list") == null || wx.getStorageSync("list") == "") {
    showCuPlanAndTask(obj);
    setTitle(obj);
    setListItemCount(obj);
  }
}
/**用户选择的第几个计划 */
var cuSelectNum = 0;

function setTitle(_this) {
  var count = 0;
  var countChecked = 0;

  for (var x = 0; x < _this.data.list.length; x++) {
    for (var y = 0; y < _this.data.list[x].item.length; y++) {
      if (_this.data.list[x].item[y].isChecked) {
        countChecked++;
      }
      count++;
    }
  }

  wx.setNavigationBarTitle({
    title: "任务 " + countChecked + "/" + count
  })
}

function setListItemCount(_this) {
  for (var x = 0; x < _this.data.list.length; x++) {
    var count = 0;
    var countChecked = 0;
    for (var y = 0; y < _this.data.list[x].item.length; y++) {
      if (_this.data.list[x].item[y].isChecked) {
        countChecked++;
      }
      count++;
    }

    _this.data.list[x].count = countChecked + "/" + count;
  }


  _this.setData({
    list: _this.data.list
  })
}

function showBottomInput(_this) {
  // 显示遮罩层
  var animation = wx.createAnimation({
    duration: 300,
    timingFunction: "ease-in-out",
    delay: 0
  })
  _this.animation = animation
  animation.translateY(100).step();

  if (_this.data.buttonText == '') {
    var btnText = '暂无计划';
    if (_this.data.list.length > 0) {
      btnText = _this.data.list[0].listName;
    } else {
      btnText = '暂无计划';
    }

    _this.setData({
      buttonText: btnText
    })
  }

  _this.setData({
    animationData: animation.export(),
    showModalStatus: true,
    isBlur: true,
    isPlayScale: "animation: scaleMoveIn 0.1s linear;animation-fill-mode: forwards;",
  })
  setTimeout(function() {
    animation.translateY(0).step()
    _this.setData({
      animationData: animation.export()
    })
  }.bind(_this), 0)
}

function hideBottomInput(_this) {
  // 隐藏遮罩层
  var animation = wx.createAnimation({
    duration: 300,
    timingFunction: "ease-in-out",
    delay: 0
  })
  _this.animation = animation
  animation.translateY(100).step()
  _this.setData({
    animationData: animation.export(),
    isBlur: false,
    isPlayScale: "animation: scaleMoveOut 0.1s linear;animation-fill-mode: forwards;"
  })
  setTimeout(function() {
    animation.translateY(0).step()
    _this.setData({
      animationData: animation.export(),
      showModalStatus: false,
    })
  }.bind(_this), 0)
}

function playTextAnim(_this) {
  //zzp2
  var animation = wx.createAnimation({
    duration: 100,
    transformOrigin: '0 0',
    timingFunction: 'ease-out', // "linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end"
  })

  _this.animation = animation

  animation.opacity(1).scale(1, 0).step({
    duration: 1
  });
  animation.opacity(1).scale(1, 1).step();

  _this.setData({
    animationDataItem: animation.export()
  })
}

Page({
  data: {
    this_cuSelectNum: cuSelectNum,
    isArrowShow: "none",
    isArrowShowFirst: "none",
    mt: 0,
    liststartTime: 0,
    listendTime: 0,
    openid: "",
    session_key: "",
    isScope: false,
    isPlayScale: "",
    touch_start: 0,
    touch_end: 0,
    checkBg: "#fff",
    isBlur: false,
    showModalStatus: false,
    isInputShow: "none",
    itemOpacity: 0,
    animationData: {},
    animationDataItem: {},
    transform: {},
    searchinput: "",
    createPlan: "",
    hiddenmodalput: true,
    listName: [],
    isFinsh: false,
    intputValue: "",
    buttonText: "",
    list: wx.getStorageSync("list"),
    // [{
    //   listName: '默认计划',
    //   item: [{
    //     itemName: 'a-1',
    //     content: '1-1中的内容',
    //     time: '2015-05-06',
    //     isChecked: false
    //   }, {
    //     itemName: 'a-2',
    //     content: '1-2中的内容',
    //     time: '2015-04-13'
    //   }, {
    //     itemName: 'a-3',
    //     content: '1-3中的内容',
    //     time: '2015-12-06',
    //     isChecked: false
    //   }]
    // }, {
    //   listName: '第二计划',
    //   item: [{
    //     itemName: 'a-1',
    //     content: '1-1中的内容',
    //     time: '2015-05-06',
    //     isChecked: false
    //   }, {
    //     itemName: 'a-2',
    //     content: '1-2中的内容',
    //     time: '2015-04-13',
    //     isChecked: false
    //   }, {
    //     itemName: 'a-3',
    //     content: '1-3中的内容',
    //     time: '2015-12-06',
    //     isChecked: false
    //   }]
    // }]
  },
  cldClick: function(e) {
    wx.navigateTo({
      url: 'calendar/calendar',
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })

    
  },
  sss: function(e) {
    wx.request({
      url: getApp().globalData.url + '/loginMain/getAccessToken',
      data: {
        userId: wx.getStorageSync("userId"),
        formId: subid
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {

      }
    })
  },
  formReset: function(e) {
    console.log("formReset", e);
  },
  sub: function(e) {
    var obj = this;
    console.log("sub", e);
    subid = e.detail.formId;
    if (e.detail.target.id == 'a') {
      obj.send();
    }
    /**
     * 收集formId
     */
    setFormId(obj);
  },
  goOutBtn1: function(e) {
    this.setData({
      isArrowShowFirst: "none"
    })
    this.showModal();
  },
  goOutBtn: function(e) {
    this.setData({
      isArrowShow: "none",
    })
    wx.navigateTo({
      url: '../team/team?planName=' + this.data.list[0].listName +
        '&planId=' + this.data.list[0].listId,
    })
  },
  goOut: function(e) {
    this.setData({
      isArrowShow: "none",

    })
  },
  intoTeam: function(e) {
    wx.navigateTo({
      url: '../team/team?planName=' + this.data.list[e.target.id].listName +
        '&planId=' + this.data.list[e.target.id].listId,
    })
  },
  /** * 页面的初始数据 */
  actioncnt: function() {
    var itemListTemp = new Array();
    for (var i = 0; i < this.data.list.length; i++) {
      itemListTemp.push(this.data.list[i].listName);
    }
    this.setData({
      listName: itemListTemp,
      hiddenmodalput: false
    })
  },
  cancelM: function(e) {
    this.setData({
      hiddenmodalput: true,
    })
  },

  confirmM: function(e) {
    if (this.data.createPlan == "") {
      wx.showToast({
        title: '计划名称不能为空',
        icon: 'none',
        duration: 1000,
        mask: true,
        success: function(res) {},
        fail: function(res) {},
        complete: function(res) {},
      })
      return;
    }
    var listTemp = new Array();
    listTemp = this.data.list;
    var listAdd = {
      listName: this.data.createPlan,
      item: []
    };

    listTemp.push(listAdd);
    // hideBottomInput(this);
    wx.setStorageSync("list", this.data.list);
    setListItemCount(this);

    this.setData({
      list: listTemp,
      hiddenmodalput: true,
      createPlan: "",
      searchinput: ""
    })

    let Index = listTemp.length - 1, //获取点击的下标值 
      list = this.data.list;
    // console.log(Index);
    cuSelectNum = Index;

    this.setData({
      this_cuSelectNum: cuSelectNum
    })

    list[Index].show = !list[Index].show || false; //变换其打开、关闭的状态
    if (list[Index].show) { //如果点击后是展开状态，则让其他已经展开的列表变为收起状态 
      this.packUp(list, Index);
    }

    var btnText = "";
    if (list.length > 0) {
      btnText = list[Index].listName;
    }
    if (getApp().globalData.isOnline)
      sendData(this, 0);
    this.setData({
      buttonText: btnText,
      list,
      hiddenmodalput: true
    })
  },

  iName: function(e) {
    this.setData({
      createPlan: e.detail.value
    })
  },
  //选中某一个计划
  planClick: function(e) {
    /**
     * 点击下方选择了以及栏目之后展开相应栏目
     */
    let Index = e.currentTarget.dataset.parentindex, //获取点击的下标值 
      list = this.data.list;

    if (cuSelectNum != Index) {
      cuSelectNum = Index;

      this.setData({
        buttonText: list[Index].listName,
        list,
        this_cuSelectNum: cuSelectNum
      });

      list[Index].show = !list[Index].show || false; //变换其打开、关闭的状态
      if (list[Index].show) { //如果点击后是展开状态，则让其他已经展开的列表变为收起状态 
        this.packUp(list, Index);
      }
      // hideBottomInput(this);

      this.setData({
        buttonText: list[Index].listName,
        list,
        hiddenmodalput: true
      })
    } else {
      // hideBottomInput(this);
      this.setData({
        hiddenmodalput: true
      })
    }
  },
  //点击最外层列表展开收起 
  listTap(e) {
    if (this.listendTime - this.liststartTime < 350) {
      let Index = e.currentTarget.dataset.parentindex, //获取点击的下标值 
        list = this.data.list;
      list[Index].show = !list[Index].show || false; //变换其打开、关闭的状态
      if (list[Index].show) { //如果点击后是展开状态，则让其他已经展开的列表变为收起状态 
        this.packUp(list, Index);
      }
      cuSelectNum = Index;

      this.setData({
        buttonText: list[Index].listName,
        list,
        this_cuSelectNum: cuSelectNum
      });
    }
  }, //点击里面的子列表展开收起
  listItemTap(e) {
    //zzp
    let parentindex = e.currentTarget.dataset.parentindex, //点击的内层所在的最外层列表下标 
      Index = e.currentTarget.dataset.index, //点击的内层下标 
      list = this.data.list;
    // console.log(list[parentindex].item, Index);
    list[parentindex].item[Index].show = !list[parentindex].item[Index].show || false; //变换其打开、关闭的状态 
    if (list[parentindex].item[Index].show) { //如果是操作的打开状态，那么就让同级的其他列表变为关闭状态，保持始终只有一个打开 
      for (let i = 0, len = list[parentindex].item.length; i < len; i++) {
        if (i != Index) {
          list[parentindex].item[i].show = false;
        }
      }
    }
    this.setData({
      list
    });
  }, //让所有的展开项，都变为收起 
  packUp(data, index) {
    for (let i = 0, len = data.length; i < len; i++) { //其他最外层列表变为关闭状态
      if (index != i) {
        data[i].show = false;
        for (let j = 0; j < data[i].item.length; j++) { //其他所有内层也为关闭状态
          data[i].item[j].show = false;
        }
      }
    }

    this.setData({
      animationDataItem: {}
    })
  },
  onLoad: function(options) {
    var obj = this;
    var t1 = new Date().getDate();
    var t2 = new Date()
    var t = new Date(t2 - t1 + 16 * 3600 * 1000)
    console.log(t1);

    if (getApp().globalData.isScope) {
      obj.setData({
        isScope: true
      })
    }

    // 查看是否授权
    wx.getSetting({
      success: function(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function(res) {
              wx.setStorageSync("nickName", res.userInfo.nickName);
              wx.setStorageSync("avatarUrl", res.userInfo.avatarUrl);
              updateUserAvatar(res.userInfo.avatarUrl);

              obj.setData({
                isScope: true
              })
            },
            fail: function(e) {
              // console.log(e);
              obj.setData({
                isScope: false
              })
            }
          })
        } else {
          obj.setData({
            isScope: false
          })
        }
      }
    })

    if (!wx.getStorageSync("isScope") || wx.getStorageSync("userId") == "") {
      wx.navigateTo({
        url: '../scope/scope',
      })
    }

  },
  scope: function(e) {
    if (e.detail.errMsg.match("ok")) {
      wx.setStorageSync("avatarUrl", e.detail.userInfo.avatarUrl);
      wx.setStorageSync("nickName", e.detail.userInfo.nickName);
      updateUserAvatar(e.detail.userInfo.avatarUrl);
      this.setData({
        isScope: true
      })
    } else {
      this.setData({
        isScope: false
      })
    }
  },
  /** * 生命周期函数--监听页面初次渲染完成 */
  onReady: function() {},
  /** * 生命周期函数--监听页面显示 */
  onShow: function() {
    var obj = this;

    wx.getNetworkType({
      success: function(res) {
        // 返回网络类型, 有效值：
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        var networkType = res.networkType
        if (res.networkType != "none") {
          if (getApp().globalData.isOnline && wx.getStorageSync("isScope")) {
            if (wx.getStorageSync("userId") == "") {
              wx.navigateTo({
                url: '../scope/scope',
              })
            } else {
              updateUserInfo(obj);
              sendData(obj, cuSelectNum);
              // doHttp(obj);
            }
          }
        }
      }
    })

    if (wx.getStorageSync("isFirst") == '') {
      obj.setData({
        isArrowShowFirst: ""
      })
    }


    wx.request({
      url: getApp().globalData.url + '/loginMain/getShareInfo',
      data: {},
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        console.log("getShareInfo", res);
        obj.share_title = res.data.title;
        obj.share_image = res.data.image_url;

      },
      fail: function(e) {
        console.log(e);
      }
    })
  },
  /** * 生命周期函数--监听页面隐藏 */
  onHide: function() {},
  /** * 生命周期函数--监听页面卸载 */
  onUnload: function() {},
  /** * 页面相关事件处理函数--监听用户下拉动作 */
  onPullDownRefresh: function() {
    // doHttp(this);
    sendData(this);
  },
  /** * 页面上拉触底事件的处理函数 */
  onReachBottom: function() {},
  /** * 用户点击右上角分享 */
  onShareAppMessage: function(e) {
    var obj = this;
    console.log("share_title", obj.share_title);
    console.log("share_image", obj.share_image);
    if (e.from === 'button') {
      // 来自页面内转发按钮
      console.log(e)
    }
    // + "&userName="
    return {
      title: obj.share_title,
      // imageUrl: "../images/share.png",
      imageUrl: obj.share_image,
    }
  },
  //获取底部文本框的值
  inputText: function(e) {
    this.setData({
      intputValue: e.detail.value
    })
  },
  inputTextf: function(e) {},
  inputTextb: function(e) {

  },
  bindTouchStart: function(e) {
    this.startTime = e.timeStamp;
  },
  bindTouchEnd: function(e) {
    this.endTime = e.timeStamp;
  },
  listTouchStart: function(e) {
    this.liststartTime = e.timeStamp;
  },
  listTouchEnd: function(e) {
    this.listendTime = e.timeStamp;
  },
  checkboxChange: function(e) {
    var obj = this;

    if (this.endTime - this.startTime < 350) {
      var isChecked = e.target.dataset.checks ? false : true;
      // console.log(isChecked);

      var index = parseInt(e.currentTarget.dataset.index);
      if (this.data.list[cuSelectNum].item[index].isChecked) {
        this.data.list[cuSelectNum].item[index].isChecked = false;
      } else {
        this.data.list[cuSelectNum].item[index].isChecked = true;
      }

      setChecked(this, this.data.list[cuSelectNum].item[index].itemId, this.data.list[cuSelectNum].item[index].isChecked, index)

    }
  },
  send: function(e) {
    var obj = this;
    if (obj.data.list.length <= 0) {
      wx.showModal({
        title: '添加计划',
        content: '请先添加该任务所选择的计划',
        showCancel: true,
        cancelText: '不要',
        cancelColor: '#cccccc',
        confirmText: '去添加',
        confirmColor: '#7db8ec',
        success: function(res) {
          var itemListTemp = new Array();
          for (var i = 0; i < obj.data.list.length; i++) {
            itemListTemp.push(obj.data.list[i].listName);
          }
          obj.setData({
            listName: itemListTemp,
            hiddenmodalput: false
          })
        },
        fail: function(res) {

        },
        complete: function(res) {},
      })
      return;
    }

    if (this.data.intputValue != "") {
      var listTemp = new Array();
      listTemp = obj.data.list;
      var itemTemp = new Array();
      obj.data.list[cuSelectNum].item = [{
        itemName: obj.data.intputValue,
        content: '1-1中的内容',
        time: '2015-05-06',
        isChecked: false
      }].concat(obj.data.list[cuSelectNum].item);

      if (!obj.data.list[cuSelectNum].show) {
        obj.data.list[cuSelectNum].show = true;
      }
      wx.setStorageSync("list", obj.data.list);
      setListItemCount(obj);
      playTextAnim(obj);
      //zzp1
      setTitle(obj);
      hideBottomInput(obj);

      if (getApp().globalData.isOnline) {
        sendData(obj, cuSelectNum);
      }
    } else {
      wx.showModal({
        content: '请输入字符',
        showCancel: false, //不显示取消按钮
        confirmText: '确定'
      })
    }
  },
  showModal: function() {
    var _this = this;
    showBottomInput(_this);
  },
  hideModal: function() {
    hideBottomInput(this)
  },
  checkboxTouchStart: function(e) {
    let that = this;
    that.setData({
      touch_start: e.timeStamp
    })
  },
  checkboxTouchEnd: function(e) {
    let that = this;
    that.setData({
      touch_end: e.timeStamp
    })
  },
  checkboxLongClick: function(e) {
    var clickNum = e.currentTarget.dataset.index;
    var obj = this;

    wx.showModal({
      title: '提示',
      content: '确定要删除' + this.data.list[cuSelectNum].item[clickNum].itemName + "吗？",
      success: function(res) {
        if (res.confirm) {
          if (getApp().globalData.isOnline)
            deleteTask(obj, obj.data.list[cuSelectNum].item[clickNum].itemId);

          //确定          
          setListItemCount(obj);
          obj.data.list[cuSelectNum].item.splice(clickNum, 1);
          setListItemCount(obj);
          // console.log("listTemp.length", obj.data.list.length);


          obj.setData({
            list: obj.data.list,
          })
        } else if (res.cancel) {
          //取消
        }
      }
    })
  },
  listLongClick: function(e) {

    var clickNum = e.currentTarget.dataset.index;
    var obj = this;
    // console.log(clickNum);
    wx.showModal({
      title: '提示',
      content: '确定要删除' + this.data.list[clickNum].listName + "吗？",
      success: function(res) {
        if (res.confirm) {
          if (getApp().globalData.isOnline)
            deletePlan(obj, obj.data.list[clickNum].listId);
          //确定          
          setListItemCount(obj);
          obj.data.list.splice(clickNum, 1);
          obj.setData({
            list: obj.data.list
          })
        } else if (res.cancel) {
          //取消
        }
      }
    })
  }
})

function getToken(that) {
  /**
   * 获取access_token
   */
  wx.request({
    url: "https://api.weixin.qq.com/cgi-bin/token",
    data: {
      grant_type: "client_credential",
      appid: "wx5d6db64a11aeb2de",
      secret: "ee51ab838de63f97460b5467d3342656",
    },
    method: 'GET',
    header: {
      'content-type': 'application/json'
    },
    success: function(res) {
      console.log("res.data.access_token", res.data.access_token);
      var access_tokenThis = res.data.access_token;

      wx.request({
        url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + access_tokenThis,
        data: {

          touser: "oJ7zx5Nz56awi6H4wdVta8F54q-g",
          // touser:"oJ7zx5GbvaWJPSp35rXxNrJZ0X9A",
          template_id: "rQJBf1QLQEU01N2tR_g_90tPheB5QGwpMCn3VrZgedU",
          form_id: subid,
          data: "123",
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: function(e) {
          console.log("acc", e);
        }
      })
      // wx.request({
      //   url: getApp().globalData.url +"/PLanAndTask/sendMessage",
      //   data: {
      //     access_token: access_tokenThis,
      //   },
      //   method: 'POST',
      //   header: {
      //     // 'content-type': 'application/json'
      //     'content-type': 'application/x-www-form-urlencoded'
      //   },
      //   success: function(res) {
      //     console.log("sendMessage", res);


      //   }
      // })
    }
  })
}

function setFormId(obj) {
  wx.request({
    url: getApp().globalData.url + '/loginMain/setFormId',
    data: {
      user_id: wx.getStorageSync("userId"),
      formId: subid
    },
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {

    }
  })
}

function getAccToken(obj) {
  wx.request({
    url: getApp().globalData.url + '/loginMain/getAccessToken',
    data: {
      userId: wx.getStorageSync("userId")
    },
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {

    }
  })
}